package com.atguigu.orderservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.orderservice.entity.Order;
import com.atguigu.orderservice.service.OrderService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-02-07
 */
@RestController
@RequestMapping("/orderservice/order")
//@CrossOrigin
public class OrderController {

    @Autowired
    private OrderService orderService;

    //1、生成订单方法
    @PostMapping("createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request){
        //通过token获取用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);

        if(StringUtils.isEmpty(memberId)){
           return R.error().code(28004);
        }

        //创建订单，返回订单号
        //参数一：课程id
        //参数二：通过token获取用户id（这个方法写好了直接返回的就是用户id）
        String orderNo = orderService.createOrders(courseId,memberId);
        return R.ok().data("orderId",orderNo);
    }


    //2、根据订单id查询订单信息
    @GetMapping("getOrder/{orderId}")
    public R getOrder(@PathVariable String orderId) {
        //条件：根据（order_no：订单id）
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        //查询某一个订单
        Order order = orderService.getOne(wrapper);
        return R.ok().data("item", order);
    }


    //3、根据 用户id 和 课程id 查询表中 订单状态
    @GetMapping("isBuyCourse/{courseId}/{memberid}")
    public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberid) {
        QueryWrapper<Order> wrapper=new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id",memberid);
        wrapper.eq("status", 1);//订单状态是1表示支付成功
        int count = orderService.count(wrapper);
        if(count>0) {//已经支付
            return true;
        } else {
            return false;
        }
    }

}

